package com.example.rk.filter;
import com.example.rk.common.SessionParameter;
import com.example.rk.entity.Admin;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录过滤器
@WebFilter("/*")   //  /*表示验证过滤所有的url
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest hsr=(HttpServletRequest)servletRequest;
        HttpServletResponse hsrp=(HttpServletResponse)servletResponse;

        String url = hsr.getRequestURL().toString().toLowerCase();
        //白名单：不需要验证过滤的url,比如：登录页面，注册页面等
        if (url.contains("login")
                || url.contains("register")
                ||url.contains("style")
                ||url.contains("index")
                ||url.contains("kaptcha")
                ||url.contains("getimg")
        ) {
            filterChain.doFilter(servletRequest,servletResponse); //跳转到下一个过滤器
        }else{
            Object attribute = hsr.getSession().getAttribute(SessionParameter.ADMIN_INFO);
            if (attribute!=null && attribute instanceof Admin){
                //用户已经登录
                filterChain.doFilter(servletRequest,servletResponse); //跳转到下一个过滤器
            }else{
                hsrp.sendRedirect("/jsp/admin/login.jsp"); //用户没有登录，跳转到登录页面
            }
        }
    }
}
